package com.auto.admin.manager.impl;

import com.alibaba.fastjson.JSONObject;
import com.auto.admin.conf.MockConf;
import com.auto.admin.constants.ApplicationNameCode;
import com.auto.admin.constants.Constants;
import com.auto.admin.entity.ApiCategory;
import com.auto.admin.entity.ApiInfo;
import com.auto.admin.entity.ParamMapping;
import com.auto.admin.entity.bo.ApiInfoBO;
import com.auto.admin.entity.bo.param.ExecRequestBO;
import com.auto.admin.entity.bo.param.SaveApiInfoBO;
import com.auto.admin.manager.ApiInfoManager;
import com.auto.admin.service.ApiCategoryService;
import com.auto.admin.service.ApiInfoService;
import com.auto.admin.service.BaseMockService;
import com.auto.admin.service.ParamMappingService;
import com.auto.admin.util.RestTemplateUtil;
import com.auto.api.admin.constant.MockTypeConstants;
import com.auto.api.admin.constant.SourceTypeConstants;
import com.auto.api.common.utils.BeanMapper;
import com.auto.api.common.utils.JsonMapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

/**
 * Description:业务处理类
 *
 * @author liangshf
 * @date 2019-06-20
 */
@Service
public class ApiInfoManagerImpl implements ApiInfoManager {

    public static final String STR = "-";
    public static final String POINT = "&";
    public static final String STRING = "(";
    public static final String STRING1 = ",";
    public static final String STRING2 = ")";

    @Resource
    private ParamMappingService paramMappingService;

    @Resource
    private ApiInfoService apiInfoService;

    @Resource
    private BaseMockService baseMockService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private ApiCategoryService apiCategoryService;

    /**
     * mock 初始化标识
     */
    static  final String INIT = "init_mock";

    private static final Logger logger = LoggerFactory.getLogger(ApiInfoManagerImpl.class);

    @Async
    public void saveApiList(List<ApiInfoBO> apiInfoList) {
        List<SaveApiInfoBO> mappingList = checkApiList(apiInfoList);
        List<ApiCategory> categoryList = checkApiCategoryList(apiInfoList);
        saveApiCategoryList(categoryList);
        //组装并解析api分类
        saveApiInfoList(mappingList ,categoryList);
    }

    @Override
    public ApiInfo getById(Serializable id) {
        return apiInfoService.getById(id);
    }

    /**
     * 验证及组装新增ApiCategory信息
     *
     * @param mockMappingList List<SaveApiInfoBO>
     * @return List
     */
    private List<ApiCategory> checkApiCategoryList(List<com.auto.admin.entity.bo.ApiInfoBO> mockMappingList) {
        //旧ApiCategory
        Map<String, ApiCategory> oldApiCategoryMap = Collections.emptyMap();
        if (CollectionUtils.isNotEmpty(mockMappingList)) {
            //获取所有分类
            List<ApiCategory> categoryList = apiCategoryService.findByTopId(1L);
            if (CollectionUtils.isNotEmpty(categoryList)) {
                oldApiCategoryMap = categoryList.stream().collect(Collectors.toMap(ApiCategory::getCode, Function.identity()));
            }
        }
        String applicationName = mockMappingList.get(0).getApplicationName();
        Set<String> codeList = mockMappingList.parallelStream().map(v -> {
            String controllerName = v.getControllerName();
            String [] codes = controllerName.split(Constants.POINT);
            return codes[codes.length -2];
        }).collect(Collectors.toSet());
        // 组装ApiCategory信息
        List<ApiCategory> result = new ArrayList<>();
        for (String code : codeList) {
            ApiCategory apiCategory = oldApiCategoryMap.remove(code);
            if (apiCategory == null) {
                apiCategory = new ApiCategory();
                apiCategory.setCreatedTime(LocalDateTime.now());
                apiCategory.setCode(code);
                apiCategory.setLeaf(Constants.ONE);
                apiCategory.setLevel(2);
                apiCategory.setShowable(Constants.ONE);
                apiCategory.setStatus(Constants.ONE);
                apiCategory.setDel(Constants.ZERO);
                apiCategory.setPid(1L);
                apiCategory.setName("");
                apiCategory.setCreatedBy(1L);
                apiCategory.setUpdatedBy(1L);
                apiCategory.setName("");
                apiCategory.setParentIds("1");
                apiCategory.setUpdatedTime(LocalDateTime.now());
            }
            result.add(apiCategory);
            code = applicationName +"_"+ code;
            ApiCategory category = oldApiCategoryMap.remove(code);
            if (category == null) {
                category = BeanMapper.map(apiCategory, ApiCategory.class);
                category.setId(null);
                category.setCreatedTime(LocalDateTime.now());
                category.setCode(code);
                category.setLevel(3);
                category.setPid(apiCategory.getId() == null ? 1L: apiCategory.getId());
                category.setParentIds("1," + apiCategory.getId());
            }

            result.add(category);
        }
        return result;
    }

    /**
     * 验证及组装SaveApiInfoBO信息
     *
     * @param apiInfoList List<ApiInfoBO>
     * @return List
     */
    private List<SaveApiInfoBO> checkApiList(List<ApiInfoBO> apiInfoList) {
        Map<String, ApiInfo> oldMappingMap = Collections.emptyMap();
        if (CollectionUtils.isNotEmpty(apiInfoList)) {
            String applicationName = apiInfoList.get(0).getApplicationName();
            List<ApiInfo> oldProductItemList = apiInfoService.findByApplicationName(applicationName);
            if (CollectionUtils.isNotEmpty(oldProductItemList)) {
                oldMappingMap = oldProductItemList.stream().collect(Collectors.toMap(ApiInfo::getUrlMethodName, Function.identity()));
            }
        }
        // 组装SaveApiInfoBO信息
        List<SaveApiInfoBO> result = new ArrayList<>();
        for (ApiInfoBO apiInfoBO : apiInfoList) {
            String urlMethodName = apiInfoBO.getRequestUrl() + apiInfoBO.getMethodName() + apiInfoBO.getRequestType();
            ApiInfo apiInfo = oldMappingMap.remove(urlMethodName);
            if (apiInfo == null) {
                apiInfo = new ApiInfo();
                apiInfo.setCreatedTime(LocalDateTime.now());
                apiInfo.setControllerRmk(apiInfoBO.getControllerRmk());
                if(apiInfoBO.getRequestUrl().startsWith(Constants.START_API)){
                    apiInfo.setFrontCategoryId(159L);
                } else {
                    apiInfo.setFrontCategoryId(-1L);
                }
                if (StringUtils.isNotEmpty(apiInfoBO.getResultJson())) {
                    JSONObject jsonObject = JSONObject.parseObject(apiInfoBO.getResultJson());
                    jsonObject.put(Constants.INIT, Constants.INIT);
                    apiInfo.setMockResultJson(JSONObject.toJSONString(jsonObject));
                }
            } else {
                if (StringUtils.isNotEmpty(apiInfoBO.getResultJson())
                        && (StringUtils.isEmpty(apiInfo.getMockResultJson()) || apiInfo.getMockResultJson().indexOf(Constants.INIT) != -1)) {
                    JSONObject jsonObject = JSONObject.parseObject(apiInfo.getResultJson());
                    if (jsonObject !=null) {
                        jsonObject.put(Constants.INIT, Constants.INIT);
                        apiInfo.setMockResultJson(JSONObject.toJSONString(jsonObject));
                    }
                }
                if (StringUtils.isNotEmpty(apiInfoBO.getControllerRmk())) {
                    apiInfo.setControllerRmk(apiInfoBO.getControllerRmk());
                }
            }
            apiInfo.setControllerName(apiInfoBO.getControllerName());
            apiInfo.setControllerRmk(apiInfoBO.getControllerRmk());
            apiInfo.setMethodRmk(apiInfoBO.getMethodRmk());
            apiInfo.setUrl(apiInfoBO.getRequestUrl());
            apiInfo.setArgs(apiInfoBO.getArgsStr());
            apiInfo.setMethodName(apiInfoBO.getMethodName());
            apiInfo.setRequestType(apiInfoBO.getRequestType());
            apiInfo.setDel(0);
            apiInfo.setResultJson(apiInfoBO.getResultJson());
            apiInfo.setResultApiJson(apiInfoBO.getResultApiJson());
            apiInfo.setParamJson(apiInfoBO.getParamJson());
            apiInfo.setParamApiJson(apiInfoBO.getParamApiJson());
            apiInfo.setAutoParamJson(apiInfoBO.getAutoParamJson());
            apiInfo.setApplicationName(apiInfoBO.getApplicationName());
            apiInfo.setPort(apiInfoBO.getPort());
            apiInfo.setUpdatedTime(LocalDateTime.now());
            SaveApiInfoBO saveApiInfoBO = BeanMapper.map(apiInfo, SaveApiInfoBO.class);
            List<ParamMapping> paramMappingList = checkParamMappingList(apiInfoBO, apiInfo);
            saveApiInfoBO.setParamMappingList(paramMappingList);
            result.add(saveApiInfoBO);
        }

        //标记已删除的项
        for (ApiInfo mapping : oldMappingMap.values()) {
            mapping.setDel(Constants.ONE);
            mapping.setUpdatedTime(LocalDateTime.now());
            SaveApiInfoBO controllerUrlMappingBO = BeanMapper.map(mapping, SaveApiInfoBO.class);
            List<ParamMapping> paramMappings = paramMappingService.findByUrlId(mapping.getId());
            //标记已删除的项
            for (ParamMapping paramMapping : paramMappings) {
                paramMapping.setDel(Constants.ONE);
                paramMapping.setUpdatedTime(LocalDateTime.now());
            }
            controllerUrlMappingBO.setParamMappingList(paramMappings);
            result.add(controllerUrlMappingBO);
        }
        return result;
    }

    private List<ParamMapping> checkParamMappingList(ApiInfoBO mockMappingBO, ApiInfo apiInfo) {
        List<ParamMapping> paramMappings = paramMappingService.findByUrlId(apiInfo.getId());
        Map<String, ParamMapping> paramMappingMap = paramMappings.stream().collect(Collectors.toMap(ParamMapping::getFullAttrName, Function.identity()));
        List<ParamMapping> paramMappingList = Lists.newArrayList();
        if (mockMappingBO.getParamMap() == null) return paramMappingList;
        mockMappingBO.getParamMap().forEach((key, value) -> {
            String attrName;
            String fullAttrName;
            if (key.indexOf(STR) != -1) {
                String[] attrKeys = key.split(STR);
                attrName = attrKeys[Constants.ZERO];
                fullAttrName = attrKeys[1];
            } else {
                attrName = key;
                fullAttrName = key;
            }
            String attrType;
            String attrRmk = "";
            if (value.indexOf(POINT) != -Constants.ONE) {
                String[] attrKeys = value.split(POINT);
                if (attrKeys.length > Constants.ONE) {
                    attrType = attrKeys[Constants.ZERO];
                    attrRmk = attrKeys[Constants.ONE];
                } else {
                    attrType = value;
                }
            } else {
                attrType = value;
            }
            ParamMapping paramMapping = new ParamMapping();
            paramMapping.setAttrName(attrName);
            paramMapping.setFullAttrName(fullAttrName);
            paramMapping.setAttrType(attrType);


            if (paramMapping.getAttrName().equals("pageNum")) {
                paramMapping.setSourceType(SourceTypeConstants.FIXED);
                paramMapping.setDicValues("1");
            }
            if (paramMapping.getAttrName().equals("pageSize")) {
                paramMapping.setSourceType(SourceTypeConstants.FIXED);
                paramMapping.setDicValues("50");
            }
            paramMapping.setDel(0);
            paramMapping.setAttrRmk(attrRmk);
            ParamMapping oldParamMapping = paramMappingMap.remove(paramMapping.getFullAttrName());
            if (oldParamMapping != null) {
                /*if (StringUtils.isNotEmpty(oldParamMapping.getAttrRmk()) && StringUtils.isEmpty(paramMapping.getAttrRmk())) {
                    paramMapping.setAttrRmk(oldParamMapping.getAttrRmk());
                }*/
                paramMapping.setId(oldParamMapping.getId());
            }else{
                //解析设置时需要满足规则如： 来源(1-A,2-B,3-C,4-D,5-E)
                if (attrRmk.indexOf(STRING) != -1
                        && attrRmk.indexOf(STRING1) != -1
                        && attrRmk.indexOf(STR) != -Constants.ONE) {//存在数据字典
                    String[] enums = attrRmk
                            .substring(attrRmk.indexOf(STRING) + Constants.ONE
                                    , attrRmk.indexOf(STRING2)
                            ).split(STRING1);
                    //数据字典
                    StringBuffer buffer = null;
                    for (String str: enums) {
                        if (buffer == null) {
                            buffer = new StringBuffer();
                            buffer.append(str.split(STR)[0]);
                        } else {
                            buffer.append(STRING1);
                            buffer.append(str.split(STR)[0]);
                        }
                    }
                    paramMapping.setDicValues(buffer.toString());
                    paramMapping.setSourceType(SourceTypeConstants.DIRECT);
                }
            }
            paramMappingList.add(paramMapping);
        });

        //标记已删除的项
        for (ParamMapping mapping : paramMappingMap.values()) {
            mapping.setDel(Constants.ONE);
            mapping.setUpdatedTime(LocalDateTime.now());
            paramMappingList.add(mapping);
        }
        return paramMappingList;
    }

    /**
     * 保存ApiCategory信息
     *
     * @param apiCategoryList List<ApiCategory>
     */
    private void saveApiCategoryList(List<ApiCategory> apiCategoryList) {
        if (apiCategoryList.size() > Constants.ONE) {
            apiCategoryList.sort(Comparator.comparing(p -> p.getLevel() != null ? p.getLevel() : 0L));
        }
        for (ApiCategory apiCategory : apiCategoryList) {
            if (apiCategory.getId() == null) {
                apiCategoryService.save(apiCategory);
            }
        }
    }

    /**
     *
     * 保存MockMappingBO信息
     * @param categoryList    List<ApiCategory>
     * @param saveApiInfoList List<SaveApiInfoBO>
     */
    private void saveApiInfoList(List<SaveApiInfoBO> saveApiInfoList ,List<ApiCategory> categoryList) {
        if (saveApiInfoList.size() > Constants.ONE) {
            saveApiInfoList.sort(Comparator.comparing(p -> p.getId() != null ? p.getId() : 0L));
        }
        Map<String, ApiCategory> apiCategoryMap = categoryList.stream().collect(Collectors.toMap(ApiCategory::getCode, Function.identity()));

        for (SaveApiInfoBO mapping : saveApiInfoList) {
            ApiCategory apiCategory = apiCategoryMap.get(mapping.getCode());
            mapping.setMockType(MockTypeConstants.MOCK_TYPE_N);
            if (mapping.getId() == null) {
                mapping.setCategoryId(apiCategory.getId());
                apiInfoService.save(mapping);
            } else {
                apiInfoService.updateById(mapping);
            }
            saveParamMappingList(mapping);
        }
    }

    /**
     * 保存ParamMapping信息
     *
     * @param mapping SaveApiInfoBO
     */
    private void saveParamMappingList(SaveApiInfoBO mapping) {
        List<ParamMapping> paramMappingList = mapping.getParamMappingList();
        if (CollectionUtils.isEmpty(paramMappingList)) return;
        if (paramMappingList.size() > Constants.ONE) {
            paramMappingList.sort(Comparator.comparing(p -> p.getId() != null ? p.getId() : 0L));
        }
        for (ParamMapping paramMapping : paramMappingList) {
            paramMapping.setUrlId(mapping.getId());
            if (paramMapping.getId() != null) {
                paramMapping.setUpdatedTime(LocalDateTime.now());
                paramMappingService.updateById(paramMapping);
            } else {
                paramMappingService.save(paramMapping);
            }
        }
    }

    @Override
    public ApiInfo getByUrl(String url) {
        List<ApiInfo> result = apiInfoService.findByUrl(url);
        if (CollectionUtils.isNotEmpty(result)) {
            ApiInfo apiInfo = result.get(Constants.ZERO);
            if (StringUtils.isEmpty(apiInfo.getMockResultJson())) {
                return apiInfo;
            }
            // autoParamJson 转map
            Map<String,Object> map = JSONObject.parseObject(apiInfo.getMockResultJson(),Map.class);
            if(map.get(INIT) != null){
                //替换模拟数据
                map.remove(INIT);
                apiInfo.setMockResultJson(JsonMapper.toJson(map));
            }
            return apiInfo;
        }
        return null;
    }

    @Override
    public String request(ExecRequestBO paramBO){
        if (StringUtils.isNotEmpty(paramBO.getFullUrl())) {
            return RestTemplateUtil.request(paramBO.getFullUrl()
                ,StringUtils.isEmpty(paramBO.getMethod()) || paramBO.getMethod().equalsIgnoreCase("post") ? HttpMethod.POST : HttpMethod.GET, buildHeaders(paramBO), paramBO.getParam(), String.class);
        }
        String getParam = null;
        Long id;
        //get请求参数
        if (paramBO.getId().indexOf("?") != -1) {
            String [] params = paramBO.getId().split("[?]");
            getParam = params[Constants.ONE];
            id = Long.parseLong(params[Constants.ZERO]);
        }else {
            id = Long.parseLong(paramBO.getId());
        }

        ApiInfo apiInfo = apiInfoService.getById(id);
        if (apiInfo != null) {
            try {
                String baseUrl = StringUtils.isNotEmpty(paramBO.getBaseUrl()) ? paramBO.getBaseUrl() : MockConf.base_url ;

                if (apiInfo.getUrl().startsWith("/api")) {
                    if (paramBO.getBaseUrl().indexOf("localhost") == -1 && paramBO.getBaseUrl().indexOf("127.0.0.1") == -1 && paramBO.getBaseUrl().indexOf("192") == -1) {
                        List<ServiceInstance> serviceInstances = discoveryClient.getInstances(apiInfo.getApplicationName());
                        if (CollectionUtils.isNotEmpty(serviceInstances)) {
                            baseUrl = serviceInstances.get(0).getUri().toString();
                        }
                    } else{
                        //内部服务调用本地服务
                        baseUrl = paramBO.getBaseUrl() + apiInfo.getPort();
                    }
                } else {
                    if (StringUtils.isEmpty(paramBO.getBaseUrl()) ||(StringUtils.isNotEmpty(paramBO.getBaseUrl())
                        && paramBO.getBaseUrl().indexOf("localhost") == -1 && paramBO.getBaseUrl().indexOf("127.0.0.1") == -1 && paramBO.getBaseUrl().indexOf("192") == -1)) {
                        if (StringUtils.isEmpty(paramBO.getToken())) {
                            String password;
                            if (paramBO.getBaseUrl().indexOf("dev") == -1) {
                                password = "123456";
                            } else {
                                password = "sz123456";
                            }
                            String token = baseMockService.loginAysnSuggest(baseUrl + MockConf.loginAysnSuggestUrl,"system", password
                                ,baseMockService.getPassCodeNew(baseUrl+ MockConf.getPassCodeNewUrl), "aa");
                            paramBO.setToken(token);
                        }
                        String dir = ApplicationNameCode.getDesc(apiInfo.getApplicationName());
                        baseUrl = baseUrl + String.format(MockConf.base_dir, dir);
                    } else {
                        baseUrl = baseUrl + apiInfo.getPort();
                    }
                }
                String param = StringUtils.isEmpty(paramBO.getParam()) ? apiInfo.getParamJson(): paramBO.getParam();
                if (getParam != null) {
                    param = getParam;
                }

                logger.info("baseUrl: {} --- param: {}", baseUrl + apiInfo.getUrl(), param);
                return RestTemplateUtil.request(baseUrl + apiInfo.getUrl()
                    ,StringUtils.isEmpty(paramBO.getMethod()) || paramBO.getMethod().equalsIgnoreCase("post") ? HttpMethod.POST : HttpMethod.GET, buildHeaders(paramBO), paramBO.getParam(), String.class);
            }catch (Exception e) {
                logger.info(e.getMessage());
                return e.getMessage();
            }
        }
        return "ApiInfo is null";
    }

    private MultiValueMap<String, String> buildHeaders(ExecRequestBO paramBO) {
        MultiValueMap<String, String> headers = new HttpHeaders();
        if (StringUtils.isNotEmpty(paramBO.getToken())) {
            headers.add("token", paramBO.getToken());
        }
        if (StringUtils.isNotEmpty(paramBO.getChannelId())) {
            headers.add("channel-id", paramBO.getChannelId());
        }

        if (StringUtils.isNotEmpty(paramBO.getUserId())) {
            headers.add("userId", paramBO.getUserId());
        }
        return headers;
    }

    public  List<SaveApiInfoBO> findListByParamBO(com.auto.admin.entity.bo.ApiInfoBO paramBO){
        return  BeanMapper.mapList(apiInfoService.findList(paramBO), SaveApiInfoBO.class);
    }
}
